"""
研究代理模块
"""

import json
from typing import Dict, Any
from tools.search_tools import SearchTools

class ResearchAgent:
    """研究代理"""

    def __init__(self, name: str = "研究代理"):
        self.name = name
        self.search_tools = SearchTools()
        self.retry_count = 0

    def execute(self, task: Dict[str, Any]) -> Dict[str, Any]:
        """执行研究任务"""
        print(f"🧬 {self.name} 开始工作...")

        try:
            query = task.get("query", "")
            research_scope = task.get("research_scope", "综合")

            # 执行搜索
            web_results = self.search_tools.search_web(query)
            academic_results = self.search_tools.search_academic(query)

            # 整合研究资料
            all_results = web_results + academic_results
            structured_data = self.search_tools.format_research_data(all_results)

            result = {
                "status": "success",
                "agent": self.name,
                "research_data": structured_data,
                "sources_count": len(all_results),
                "timestamp": self._get_timestamp()
            }

            print(f"✅ {self.name} 完成研究，收集到 {len(all_results)} 个资料来源")
            return result

        except Exception as e:
            self.retry_count += 1
            error_result = {
                "status": "error",
                "agent": self.name,
                "error": str(e),
                "retry_count": self.retry_count,
                "timestamp": self._get_timestamp()
            }
            return error_result

    def _get_timestamp(self) -> str:
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")